﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CIT.WMS.RM.Bll;
using CIT.WMS.Product.Bll;

namespace CIT.WMS.Product
{
    public partial class FrmTPrint_Cart : Form
    {
        public FrmTPrint_Cart()
        {
            InitializeComponent();
        }

        string _Customer = "";
        string _BoxCode = "";
        string _TuoCode = "";
        string _PalletNo = "";
        string _PN = "";
        static int _TNo = 1;
        List<string> _BoxCodes = null;

        int _BoxCount = 0;

        private void FrmTPrint_Load(object sender, EventArgs e)
        {
            InitFrm();
        }

        /// <summary>
        /// 初始化画面
        /// </summary>
        private void InitFrm()
        {
            _BoxCodes = new List<string>();

            //_Customer = "";
            _BoxCode = "";
            _TuoCode = "";
            _PalletNo = "";
            _BoxCount = 0;

            cmbCustomer.Text = "C7687";
            cmbCustomer.Enabled = false;

            txtTNo.Text = _TNo.ToString();
            txtTNo.Enabled = true;

            txtBoxCode.Text = "";
            txtBoxCode.Enabled = true;

            areaInfo.Text = "";
            areaMsg.Text = "";

            _PalletNo = GetDay();
            _TuoCode = _PalletNo;

            if (cmbLocation.Text == "")
            {
                BindLocation();
            }
        }


        private void BindLocation()
        {
            var sql = "select * from wms_B_AreaLocation";
            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, sql, new CIT.WMS.MESWcf.CmdParameter[0]);
            var row = dt.NewRow();
            dt.Rows.InsertAt(row, 0);
            if (dt.Rows.Count > 0)
            {
                cmbLocation.DataSource = dt;
                cmbLocation.DisplayMember = "ALName";
                cmbLocation.ValueMember = "ALSN";
            }
        }

        /// <summary>
        /// 1***选择客户
        /// C7687 安费诺高速技术 (南通)有限公司
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmbCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.cmbCustomer.Text == "")
            {
                areaMsg.Text = "请选择客户";
                cmbCustomer.Focus();
                return;
            }
            _Customer = this.cmbCustomer.Text;
            cmbCustomer.Enabled = false;
        }

        /// <summary>
        /// 2***托号输入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtTNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.cmbLocation.Text == "")
                {
                    areaMsg.Text = "请选择位置";
                    cmbLocation.Text = "";
                    cmbLocation.Focus();
                    return;
                }

                if (this.cmbCustomer.Text == "")
                {
                    areaMsg.Text = "请选择客户";
                    cmbCustomer.Focus();
                    return;
                }

                var qty = 0;

                try
                {
                    qty = Convert.ToInt32(txtTNo.Text);
                }
                catch (Exception ex)
                {
                    areaMsg.Text = "只能输入数字";
                    txtTNo.Text = "";
                    return;
                }

                if (qty >= 100)
                {
                    areaMsg.Text = "不能大于99";
                    txtTNo.Text = "";
                    return;
                }

                _TNo = qty;
                txtTNo.Enabled = false;
                txtPN.Focus();
            }
        }


        /// <summary>
        /// 3***箱标签输入
        /// 202S95019193
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBoxCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.cmbLocation.Text == "")
                {
                    areaMsg.Text = "请选择位置";
                    cmbLocation.Text = "";
                    cmbLocation.Focus();
                    return;
                }

                if (this.cmbCustomer.Text == "")
                {
                    areaMsg.Text = "请选择客户";
                    txtBoxCode.Text = "";
                    _BoxCode = "";
                    cmbCustomer.Focus();
                    return;
                }

                if (this.txtTNo.Enabled == true)
                {
                    areaMsg.Text = "请确认托号";
                    txtBoxCode.Text = "";
                    _BoxCode = "";
                    txtTNo.Focus();
                    return;
                }

                _BoxCode = txtBoxCode.Text;

                if (_BoxCode.StartsWith("202") == false)
                {
                    areaMsg.Text = "箱标签格式错误，请确认";
                    txtBoxCode.Text = "";
                    _BoxCode = "";
                    return;
                }

                if (_BoxCodes.Contains(_BoxCode))
                {
                    areaMsg.Text = "该箱号已扫描，请确认";
                    txtBoxCode.Text = "";
                    _BoxCode = "";
                    return;
                }

                try
                {


                    _BoxCount++;
                    _BoxCodes.Add(_BoxCode);

                    areaInfo.Text = "扫描箱数:" + _BoxCount + "\r\n";
                    //areaInfo.Text += "PSC数:" + _SumQty + "\r\n"; ;
                    areaInfo.Text += "托标签(不含流水):" + _TuoCode;
                    txtBoxCode.Text = "";
                }
                catch
                {
                    areaMsg.Text = "标签扫描异常，请尝试重新扫描";
                    txtBoxCode.Text = "";
                    _BoxCode = "";
                    return;
                }
            }

        }

        private string GetMaxNo(string fatp)
        {
            string sql = string.Format("select * from wms_T_Fatp where PalletNo like '{0}%' order by PalletNo desc", fatp);

            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, sql, new CIT.WMS.MESWcf.CmdParameter[0]);
            if (dt.Rows.Count == 0)
            {
                return fatp + "001";
            }
            else
            {
                var plt = dt.Rows[0]["PalletNo"].ToString();
                plt = plt.Substring(plt.Length - 3);
                var no = Convert.ToInt16(plt) + 1;
                return fatp + no.ToString("000");
            }
        }

        private bool IsExists(string box)
        {
            string strFlexSQL = string.Format(@"select * from wms_T_Fatp where BoxCode = '{0}' and DelFlag = 0", box);

            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, strFlexSQL, new CIT.WMS.MESWcf.CmdParameter[0]);
            return dt.Rows.Count > 0;
        }

        private bool IsExists(string fatp, string box)
        {
            string strFlexSQL = string.Format(@"select PalletNo from wms_T_Fatp where FatpCode =  '{0}' and BoxCode = '{1}' and DelFlag = 0", fatp, box);

            DataTable dt = Utils.NMS.QueryDataTable(Utils.uContext, strFlexSQL, new CIT.WMS.MESWcf.CmdParameter[0]);
            return dt.Rows.Count > 0;
        }

        /// <summary>
        /// 重置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            InitFrm();
        }

        public int GetWeekIndexByYear(DateTime dt)
        {
            // 当年第一周周末日期
            int firstWeekend = 7 - Convert.ToInt32(DateTime.Parse(dt.Year + "-1-1").DayOfWeek);
            // 当前周数
            int week = Convert.ToInt32(Math.Ceiling((dt.DayOfYear - firstWeekend) / 7.0)) + 1;
            return week;
        }

        public static string GetDateByWeekCode(string weekCode)
        {
            string year = "20" + weekCode.Substring(0, 2);
            int weekIndex = Convert.ToInt32(weekCode.Substring(2, 2));

            DateTime startOfYear = DateTime.Parse(year + "-1-1");

            DateTime result;
            if (weekIndex == 1)
            {
                result = startOfYear;
            }
            else
            {
                // 当年第一周周末日期
                int firstWeekend = 7 - Convert.ToInt32(startOfYear.DayOfWeek);
                result = startOfYear.AddDays(firstWeekend + 7 * (weekIndex - 2));

            }
            return result.ToString("yyyy-MM-dd");
        }

        public string GetDay()
        {
            DateTime date = Utils.GetSysDate();
            var day = ConvertDayToSpecialChar(date.Day);
            var month = ConvertMonthToCode(date.Month);
            return "202" + day + month + date.Year.ToString().Substring(3, 1) + "S";
        }

        /// <summary>
        /// 将日期转换为特殊字符表示
        /// 1-9: 直接显示数字
        /// 10以后按照A~Z顺序，排除I、O、Q、U
        /// </summary>
        /// <param name="day">日期（1-31）</param>
        /// <returns>转换后的字符</returns>
        private string ConvertDayToSpecialChar(int day)
        {
            if (day < 1 || day > 31)
                throw new ArgumentException("日期必须在1-31之间");

            // 1-9直接返回数字
            if (day <= 9)
                return day.ToString();

            // 定义排除的字符：I、O、Q、U
            char[] excludedChars = { 'I', 'O', 'Q', 'U' };

            // 创建可用字符列表（从A开始，排除指定字符）
            List<char> availableChars = new List<char>();
            for (char c = 'A'; c <= 'Z'; c++)
            {
                if (Array.IndexOf(excludedChars, c) == -1)
                {
                    availableChars.Add(c);
                }
            }

            // 10对应第一个可用字符A，11对应B，以此类推
            int index = day - 10;

            if (index < availableChars.Count)
            {
                return availableChars[index].ToString();
            }
            else
            {
                return "0";
            }
        }

        /// <summary>
        /// 将月份转换为编码
        /// 1-9月: 直接显示数字
        /// 10月: A, 11月: B, 12月: C
        /// </summary>
        /// <param name="month">月份（1-12）</param>
        /// <returns>月份编码</returns>
        private string ConvertMonthToCode(int month)
        {
            switch (month)
            {
                case 10: return "A";
                case 11: return "B";
                case 12: return "C";
            }
            if (month >= 1 && month <= 9)
            {
                return month.ToString();
            }
            return "0";
        }

        private void cmbCustomer_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = true;
        }

        /// <summary>
        /// 生成托标签
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (this.cmbLocation.Text == "")
            {
                areaMsg.Text = "请选择位置";
                cmbLocation.Text = "";
                cmbLocation.Focus();
                return;
            }

            if (this.cmbCustomer.Text == "")
            {
                areaMsg.Text = "请选择客户";
                cmbCustomer.Focus();
                return;
            }

            if (this.txtTNo.Enabled == true)
            {
                areaMsg.Text = "请确认托号";
                txtTNo.Focus();
                return;
            }

            if (this.txtPN.Text == "")
            {
                areaMsg.Text = "请扫描PN";
                txtPN.Focus();
                return;
            }


            if (_BoxCount == 0)
            {
                areaMsg.Text = "未扫描箱号";
                txtBoxCode.Focus();
                return;
            }

            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show("当前已扫描箱数：" + _BoxCount + ",是否生成托标签？", "打印确认", messButton, MessageBoxIcon.None, MessageBoxDefaultButton.Button1);
            if (dr == DialogResult.Cancel)
            {
                return;
            }

            var tpPlt = GetMaxNo(_PalletNo);
            var sql = "";
            foreach (var boxCode in _BoxCodes)
            {
                //                string tpSql = string.Format(@"insert into 
                //                    wms_T_Fatp (PalletNo, FatpCode, BoxCode, Customer) values 
                //                    ('{0}','{1}','{2}','{3}');", _PalletNo, _TuoCode + "," + _PalletNo, boxCode, _Customer);

                string tpSql = string.Format(@"insert into 
                    wms_T_Fatp (PalletNo, FatpCode, BoxCode, Customer) values 
                    ('{0}','{1}','{2}','{3}');", tpPlt, _PN, boxCode, _Customer);
                sql += tpSql;
            }

            //改用序列号PalletNo
            var printContent = _TNo + "," +
                            _BoxCount + "," +
                            _TuoCode;
            var username = Utils.uContext.UserNamek__BackingField;
            string tpSqlPda = "insert into wms_T_FatpPDA(PalletNo,FatpCode,FatpNo,PrintFlag,CreateTime,Creator,BoxCnt,ALSN) values ('{0}','{1}','{2}','0',getdate(),'{3}',{4},'{5}')";
            tpSqlPda = string.Format(tpSqlPda, tpPlt, _PN, _TNo, username, _BoxCount, cmbLocation.Text);
            sql += tpSqlPda;

            var sqlCmd = @"---开启事务
                begin tran
                begin try  
                " + sql
                + @"
                end try
                begin catch
                   if(@@trancount>0) --全局变量@@trancount，事务开启此值+1，他用来判断是有开启事务
                      rollback tran  ---由于出错，这里回滚到开始，第一条语句也没有插入成功。
                end catch
                if(@@trancount>0)
                commit tran";
            var ret = Utils.NMS.ExcuteSQL(sqlCmd);

            if (ret > 0)
            {
                _TNo++;
                InitFrm();
                areaMsg.Text = "生成托标签成功:" + tpPlt;
            }
            else
            {
                areaMsg.Text = "生成托标签异常";
            }
        }

        private void txtPN_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.cmbLocation.Text == "")
                {
                    areaMsg.Text = "请选择位置";
                    cmbLocation.Text = "";
                    cmbLocation.Focus();
                    return;
                }

                if (this.cmbCustomer.Text == "")
                {
                    areaMsg.Text = "请选择客户";
                    txtPN.Text = "";
                    _PN = "";
                    cmbCustomer.Focus();
                    return;
                }

                if (this.txtTNo.Enabled == true)
                {
                    areaMsg.Text = "请确认托号";
                    txtPN.Text = "";
                    _PN = "";
                    txtTNo.Focus();
                    return;
                }

                if (this.txtPN.Text == "")
                {
                    areaMsg.Text = "请扫描PN";
                    txtPN.Text = "";
                    _PN = "";
                    return;
                }

                _PN = this.txtPN.Text;

                //if (_PN.StartsWith("965") == false)
                //{
                //    areaMsg.Text = "PN格式错误，请确认";
                //    txtPN.Text = "";
                //    _PN = "";
                //    return;
                //}

                this.txtPN.Enabled = false;
            }
        }

        private void cmbLocation_KeyPress(object sender, KeyPressEventArgs e)
        {
            this.txtTNo.Focus();
        }

        //END

    }
}